package com.ymr.iot.consumer.config;

import com.ymr.iot.consumer.listener.IotJmsConnectionListener;
import com.ymr.iot.consumer.listener.IotMessageListener;
import com.ymr.iot.consumer.util.IotAuthenticationUtil;
import org.apache.qpid.jms.JmsConnection;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;

@Component
public class IotConfig implements InitializingBean {

    @Autowired
    private IotMessageListener iotMessageListener;

    @Autowired
    private IotAccountInfo iotAccountInfo;

    @Override
    public void afterPropertiesSet() throws Exception {
        String uid = iotAccountInfo.getUid();
        String regionId = iotAccountInfo.getRegionId();

        //参数说明，请参见文档：AMQP客户端接入说明。
        String accessKey = iotAccountInfo.getAccessKey();
        String accessSecret = iotAccountInfo.getAccessSecret();
        String consumerGroupId = iotAccountInfo.getConsumerGroupId();
        //iotInstanceId：购买的实例请填写实例ID，公共实例请填空字符串""。
        String iotInstanceId = iotAccountInfo.getIotInstanceId();
        long timeStamp = System.currentTimeMillis();
        //签名方法：支持hmacmd5，hmacsha1和hmacsha256。
        String signMethod = iotAccountInfo.getSignMethod();
        //控制台服务端订阅中消费组状态页客户端ID一栏将显示clientId参数。
        //建议使用机器UUID、MAC地址、IP等唯一标识等作为clientId。便于您区分识别不同的客户端。
        String clientId = iotAccountInfo.getClientId();

        //UserName组装方法，请参见文档：AMQP客户端接入说明。
        String userName = clientId + "|authMode=aksign"
                + ",signMethod=" + signMethod
                + ",timestamp=" + timeStamp
                + ",authId=" + accessKey
                + ",iotInstanceId=" + iotInstanceId
                + ",consumerGroupId=" + consumerGroupId
                + "|";
        //password组装方法，请参见文档：AMQP客户端接入说明。
        String signContent = "authId=" + accessKey + "&timestamp=" + timeStamp;
        String password = IotAuthenticationUtil.doSign(signContent, accessSecret, signMethod);
        //按照qpid-jms的规范，组装连接URL。
        String connectionUrl = String.format("failover:(amqps://%s.iot-amqp.%s.aliyuncs.com:5671?amqp.idleTimeout=80000)", uid, regionId)
                + "?failover.reconnectDelay=30";

        Hashtable<String, String> hashtable = new Hashtable<>();
        hashtable.put("connectionfactory.SBCF", connectionUrl);
        hashtable.put("queue.QUEUE", "default");
        hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
        Context context = new InitialContext(hashtable);
        ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");
        Destination queue = (Destination) context.lookup("QUEUE");
        // Create Connection
        Connection connection = cf.createConnection(userName, password);
        ((JmsConnection) connection).addConnectionListener(new IotJmsConnectionListener());
        // Create Session
        // Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。
        // Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
        // 1.收到消息之后一定要ACK。
        // 推荐做法：创建Session选择Session.AUTO_ACKNOWLEDGE，这里会自动ACK。
        // 其他做法：创建Session选择Session.CLIENT_ACKNOWLEDGE，这里一定要调message.acknowledge()来ACK。
        // message.acknowledge();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        connection.start();
        // Create Receiver Link
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener(iotMessageListener);
    }

}
